package com.qf.commons.web.exception;

import com.qf.commons.core.exception.ServiceException;
import com.qf.commons.data.result.R;
import com.qf.commons.data.result.RCodes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YaoJiXing
 * created 2022/8/16 16:24
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //全局异常捕获
    //Throwable -> 可抛出
    @ExceptionHandler
    public R catchGlobalExceptionHandler(Throwable t) {
        //System.out.println("发生了全局异常：" + t.getMessage());

        //通过日志记录当前的异常信息
        //error(String msg, Throwable t)
        log.error("全局异常被捕获：", t);
        return R.createFail(RCodes.FAIL);
    }

    //捕获参数校验异常
    @ExceptionHandler(BindException.class)
    public R catchBindExceptionHandler(BindException e) {
        List<String> errors = new ArrayList<>();
        List<String> fields = new ArrayList<>();
        /*
        	@Override
            public List<ObjectError> getAllErrors() {
                return this.bindingResult.getAllErrors();
            }
         */

        /*
        for (FieldError field : e.getFieldErrors()) {
            fields.add(field.getField());
        }
        */

        for (ObjectError error : e.getAllErrors()) {
            errors.add(error.getDefaultMessage());
        }
        return R.createFail(RCodes.DATA_CHECKED_ERROR, errors);
    }

    //业务异常捕获 - 指定捕获的异常的类型
    @ExceptionHandler(ServiceException.class)
    public R catchServiceExceptionHandler(ServiceException e) {
        //System.out.println("发生了业务异常：" + e.getMessage());
        //返回ServiceException异常对象中的数据
        return R.createFail(e.getCode(), e.getMsg());
    }


}
